package zd.cornermemory.fragment.remember;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

import greendao.RememberCjDao;
import zd.cornermemory.R;
import zd.cornermemory.db.GreenDaoManager;
import zd.cornermemory.db.RememberCj;
import zd.cornermemory.ui.RemeberCjActivity;
import zd.cornermemory.utils.CodeUtil;
import zd.cornermemory.utils.SPUtils;
import zd.cornermemory.utils.SpKey;
import zd.cornermemory.utils.Statistics;
import zd.cornermemory.utils.Utils;

import static android.content.Context.CLIPBOARD_SERVICE;
import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by zhud on 2019/4/29.
 */

public class CEFragment extends Fragment implements View.OnClickListener{

    private TextView startButton;
    private TextView input;
    private TextView check;
    private Button cj_button;
    private TextView code_text;
    private TextView edge_code_text;
    private RadioGroup radio_group;
    private RadioGroup radio_group_edge;
    private int cornerTeam = 3;//
    private int edgeTeam = 3;//
    private EditText ans;
    private String currentAns = "";
    private       LinearLayout ans_layout;
    private       String       cornerCurrentType;//默认3
    private       String       edgeCurrentType;//默认3
    private LinearLayout remember_code_layout;
    private Context mContext;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab1_ce, container, false);
        mContext = getActivity();
        rememberCjDao =  GreenDaoManager.getInstance().getNewSession().getRememberCjDao();
        startButton = view.findViewById(R.id.start_button);
        remember_code_layout = view.findViewById(R.id.remember_code_layout);
        ans_layout = view.findViewById(R.id.ans_layout);
        input = view.findViewById(R.id.input);
        check = view.findViewById(R.id.check);
        cj_button = view.findViewById(R.id.cj_button);
        code_text = view.findViewById(R.id.code_text);
        edge_code_text = view.findViewById(R.id.edge_code_text);
        radio_group = view.findViewById(R.id.radio_group);
        radio_group_edge = view.findViewById(R.id.radio_group_edge);
        ans = view.findViewById(R.id.ans);
        cornerCurrentType = SPUtils.getInstance().getString(SpKey.REMEMBER_ALL_CORNER_TYPE, "3");
        edgeCurrentType = SPUtils.getInstance().getString(SpKey.REMEMBER_ALL_EDGE_TYPE, "3");
        startButton.setOnClickListener(this);
        input.setOnClickListener(this);
        check.setOnClickListener(this);
        cj_button.setOnClickListener(this);

        code_text.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                String scr = code_text.getText().toString();
                if(Build.VERSION.SDK_INT > 11) {
                    android.content.ClipboardManager clip = (android.content.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                    clip.setPrimaryClip(ClipData.newPlainText("text", scr));
                }
                else {
                    android.text.ClipboardManager clip = (android.text.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                    clip.setText(scr);
                }
                Toast.makeText(mContext, getString(R.string.copyed_code), Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        edge_code_text.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                String scr = edge_code_text.getText().toString();
                if(Build.VERSION.SDK_INT > 11) {
                    android.content.ClipboardManager clip = (android.content.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                    clip.setPrimaryClip(ClipData.newPlainText("text", scr));
                }
                else {
                    android.text.ClipboardManager clip = (android.text.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                    clip.setText(scr);
                }
                Toast.makeText(mContext, getString(R.string.copyed_code), Toast.LENGTH_SHORT).show();
                return true;
            }
        });


        ans.setTransformationMethod(new UpperCaseTransform());
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.three_five_radio:
                        cornerTeam = 0;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_CORNER_TYPE,"0");
                        break;
                    case R.id.three_radio:
                        cornerTeam = 1;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_CORNER_TYPE,"1");
                        break;
                    case R.id.four_radio:
                        cornerTeam = 2;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_CORNER_TYPE,"2");
                        break;
                    case R.id.five_radio:
                        cornerTeam = 3;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_CORNER_TYPE,"3");
                        break;
                }
            }
        });

        switch (cornerCurrentType) {
            case "0":
                radio_group.check(R.id.three_five_radio);
                cornerTeam = 0;
                break;
            case "1":
                radio_group.check(R.id.three_radio);
                cornerTeam = 1;
                break;
            case "2":
                radio_group.check(R.id.four_radio);
                cornerTeam = 2;
                break;
            case "3":
                radio_group.check(R.id.five_radio);
                cornerTeam = 3;
                break;

        }

        radio_group_edge.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.radio_0:
                        edgeTeam = 0;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_EDGE_TYPE,"0");
                        break;
                    case R.id.radio_1:
                        edgeTeam = 1;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_EDGE_TYPE,"1");
                        break;
                    case R.id.radio_2:
                        edgeTeam = 2;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_EDGE_TYPE,"2");
                        break;
                    case R.id.radio_3:
                        edgeTeam = 3;
                        SPUtils.getInstance().put(SpKey.REMEMBER_ALL_EDGE_TYPE,"3");
                        break;
                }
            }
        });

        switch (edgeCurrentType) {
            case "0":
                radio_group_edge.check(R.id.radio_0);
                edgeTeam = 0;
                break;
            case "1":
                radio_group_edge.check(R.id.radio_1);
                edgeTeam = 1;
                break;
            case "2":
                radio_group_edge.check(R.id.radio_2);
                edgeTeam = 2;
                break;
            case "3":
                radio_group_edge.check(R.id.radio_3);
                edgeTeam = 3;
                break;
        }

        ans.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(!TextUtils.isEmpty(ans.getText().toString().trim()))
                    remember_code_layout.setVisibility(View.INVISIBLE);
            }
        });

        ans.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                checkAnswer();
                return true;
            }
        });

        //第一次进入先自动生成编码
        createCode();
        return view;
    }

    @Override
    public void onClick(View view) {
        hideSoftInput();
        switch (view.getId()) {
            case R.id.start_button:
                createCode();
                break;
            case R.id.input:
                inputAnswer();
                break;

            case R.id.check:
                checkAnswer();
                break;
            case R.id.cj_button:
                Intent intent = new Intent(getActivity(), RemeberCjActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("currentPos",0);
                bundle.putInt("type",2);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

    private void hideSoftInput() {
        try{
            InputMethodManager mInputMethodManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
            assert mInputMethodManager != null;
            mInputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

        }catch (Exception e){

        }
    }

    private void inputAnswer() {
        mRememberTime = (int)(System.currentTimeMillis()-mStartTime);
        remember_code_layout.setVisibility(View.INVISIBLE);
        ans.setText("");
        ans_layout.setVisibility(View.VISIBLE);
        Utils.showKeyboard(ans);
    }

    private int errorCount = 0;//当前编码错误次数
    private long mStartTime;//记忆开始时间
    private int mRememberTime = -1;//记忆分段
    private RememberCjDao rememberCjDao;
    private void checkAnswer() {
        if (isFastDoubleClick()) {
            return;
        }
        String ansStr = ans.getText().toString().trim();
        ansStr = ansStr.replace(" ", "");
        if (TextUtils.isEmpty(ansStr)) {
            return;
        }
        remember_code_layout.setVisibility(View.VISIBLE);
        ans_layout.setVisibility(View.VISIBLE);

        if(!ansStr.toUpperCase().equals(currentAns)){

            new AlertDialog.Builder(getActivity())
                    .setTitle(getString(R.string.alert))
                    .setMessage(getString(R.string.hdcw_jiafa))
                    .setCancelable(false)
                    .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ans.requestFocus();
                            errorCount++;
                            dialog.dismiss();
                        }
                    }).show();


        }else{
            String timeStr = "";
            int time = (int)(System.currentTimeMillis()-mStartTime);//总用时
            if(time>1000*60*60){//如果时间大于一小时，则提示时间长久了
                timeStr = getString(R.string.too_long);
            }else {
                String rememberStr = Statistics.timeToString(mRememberTime);

                int opre = (int)(time-mRememberTime);//操作时间
                String opreStr = Statistics.timeToString(opre);

                int error = errorCount*10000;//罚时
                String errorStr = Statistics.timeToString(error);


                int showTime = time+error;
                String showTimeStr = Statistics.timeToString(showTime);

                timeStr+=showTimeStr;
                timeStr+="  ( "+rememberStr+" + "+opreStr;

                if (error != 0) {
                    timeStr+= " + "+errorStr+" )";
                }else {
                    timeStr+=" )";
                }

                saveCj(error,time,mRememberTime);

            }
            new AlertDialog.Builder(getActivity())
                    .setTitle(getString(R.string.alert))
                    .setMessage(getString(R.string.ans_ok)+"\n"+getString(R.string.time_)+timeStr)
                    .setCancelable(false)
                    .setPositiveButton(getString(R.string.next_team), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ans.setText("");
                            ans_layout.setVisibility(View.INVISIBLE);
                            createCode();
                            dialog.dismiss();
                        }
                    }).show();

        }
    }

    //保存当前成绩
    private void saveCj(int error, int time,int rememberTime) {
        Long date = System.currentTimeMillis();
        RememberCj rememberCj = new RememberCj();
        rememberCj.setDate(date);
        rememberCj.setSingTime(time);
        rememberCj.setErrorTime(error);
        rememberCj.setRememberTime(rememberTime);
        rememberCj.setCode(cornerAns);
        rememberCj.setEdgeCode(edgeAns);
        rememberCj.setStatus(error!=0?2:0);
        rememberCj.setGroup(0);
        rememberCj.setType(2);
        rememberCjDao.insert(rememberCj);
    }

    private String edgeAns;
    private String cornerAns;

    //生成编码
    private void createCode() {
        remember_code_layout.setVisibility(View.VISIBLE);

        ans.setText("");
        ans_layout.setVisibility(View.INVISIBLE);

        int count = 5;
        switch (cornerTeam) {
            case 0:
                count = getCornerRandom();
                break;
            case 1:
                count = 3;
                break;
            case 2:
                count = 4;
                break;
            case 3:
                count = 5;
                break;
        }
        String codes = CodeUtil.getCornerCode(count);
        String str = getString(R.string.corner_code_2);
        codes = codes.substring(str.length(),codes.length()-1);
        code_text.setText(codes);

        String[] c = codes.split("  ");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < c.length; i++) {
            sb.append(c[i].trim());
        }
        cornerAns = sb.toString();

        int EdgeCount = 5;
        switch (edgeTeam) {
            case 0:
                EdgeCount = getEdgeRandom();
                break;
            case 1:
                EdgeCount = 6;
                break;
            case 2:
                EdgeCount = 7;
                break;
            case 3:
                EdgeCount = 8;
                break;
        }

        String EdgeCodes = CodeUtil.getEdgeCode(EdgeCount);
        String strEdge = getString(R.string.edge_code_2);
        EdgeCodes = EdgeCodes.substring(strEdge.length(),EdgeCodes.length()-1);
        edge_code_text.setText(EdgeCodes);

        String[] cE = EdgeCodes.split("  ");
        StringBuffer sbE = new StringBuffer();
        for (int i = 0; i < cE.length; i++) {
            sbE.append(cE[i].trim());
        }
        edgeAns = sbE.toString();


        currentAns = edgeAns+cornerAns;

        //生成编码，默认开始计时
        mStartTime = System.currentTimeMillis();
        errorCount = 0;
        mRememberTime=-1;
    }

    private int getCornerRandom(){
        int t ;
        Random random = new Random();
        t = random.nextInt(5);
        if(t<2){
            return getCornerRandom();
        }
        return t;
    }

    private int getEdgeRandom(){
        int t ;
        Random random = new Random();
        t = random.nextInt(8);
        if(t<5){
            return getEdgeRandom();
        }
        return t;
    }

    //首先是小写转大写的方法
    public class UpperCaseTransform extends ReplacementTransformationMethod {
        @Override
        protected char[] getOriginal() {
            char[] aa = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            return aa;
        }

        @Override
        protected char[] getReplacement() {
            char[] cc = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            return cc;
        }
    }

    private static final int TIME = 1000;
    private static long lastClickTime = 0;
    /**
     * 处理快速双击，多击事件，在TIME时间内只执行一次事件
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long currentTime = System.currentTimeMillis();
        long timeInterval = currentTime - lastClickTime;
        if (0 < timeInterval && timeInterval < TIME) {
            return true;
        }
        lastClickTime = currentTime;
        return false;
    }

}
